package com.tz.water.controller.admin;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tz.water.bean.Admin;
import com.tz.water.config.AccessLimit;
import com.tz.water.mapper.AdminMapper;
import com.tz.water.mapper.UserMapper;
import com.tz.water.utils.MyPasswordEncoder;
import com.tz.water.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/admin")
public class AdminLogin {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    UserMapper userMapper;


    @AccessLimit(times = 5)
    @PostMapping("/login")
    @ResponseBody
    public HashMap<String,Object> login (@RequestBody Admin admin, HttpServletRequest request) {
        Admin realadmin = adminMapper.selectById(1);
        MyPasswordEncoder passwordEncoder = new MyPasswordEncoder();
        if(admin.getName().equals(realadmin.getName()) && passwordEncoder.matches(admin.getPassword(),realadmin.getPassword()) ){
            request.getSession().setAttribute("loginrole","admin");
            System.out.println("sessionid :" + request.getSession().getId());
            return ResponseUtils.success("login success:" ); // 2021nngdf
        }
        return ResponseUtils.fail("login fail :" + realadmin.getPassword() +" .. " + passwordEncoder.encode(admin.getPassword()));
    }

    @AccessLimit(times = 5)
    @PostMapping("/logout")
    public HashMap<String,Object> logout (@RequestBody Admin admin, HttpServletRequest request) {
        request.getSession().setAttribute("loginrole",null);
        request.getSession().setAttribute("loginid",null);
        return ResponseUtils.notlogin("login fail ");
    }

    @AccessLimit(times = 5)
    @PostMapping("/changepass")
    public HashMap<String,Object> changepass (@RequestBody Admin admin, HttpServletRequest request) {
        if(request.getSession().getAttribute("loginrole") != null && request.getSession().getAttribute("loginrole").equals("admin")){
            Admin realadmin = adminMapper.selectById(1);
            MyPasswordEncoder passwordEncoder = new MyPasswordEncoder();
            realadmin.setPassword(passwordEncoder.encode(admin.getPassword()));
            if(adminMapper.updateById(realadmin) >0){
                return ResponseUtils.success("change success");
            }

        }
        return ResponseUtils.notlogin("login fail");
    }
}
